package com.watson.jpa.result;


import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.List;

//import redis.clients.jedis.Jedis;

/**
 * Spring MVC 配置
 *
 * @author tousen
 */
@Configuration
@Component
public class AppWebMvcConfigurer implements WebMvcConfigurer {
    private final Logger logger = LoggerFactory.getLogger(AppWebMvcConfigurer.class);


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullNumberAsZero);
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        exceptionResolvers.add(new HandlerExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
                ObjectRestResponse result = new ObjectRestResponse();
                if (e instanceof ServiceException) {
                    result.setCode(500);
                    result.setMsg(e.getMessage());
                    logger.info(e.getMessage());
                } else if (e instanceof NoHandlerFoundException) {
                    result.setCode(500);
                    result.setMsg("接口 [" + request.getRequestURI() + "] 不存在");
                } else if (e instanceof ServletException) {
                    result.setCode(500);
                    result.setMsg(e.getMessage());
                } else {
                    result.setCode(500);
                    result.setMsg("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
                    String message;
                    if (handler instanceof HandlerMethod) {
                        HandlerMethod handlerMethod = (HandlerMethod) handler;
                        message = String.format("接口 [%s] 出现异常，方法：%s.%s，异常摘要：%s",
                                request.getRequestURI(),
                                handlerMethod.getBean().getClass().getName(),
                                handlerMethod.getMethod().getName(),
                                e.getMessage());
                    } else {
                        message = e.getMessage();
                    }
                    logger.error(message, e);
                }
                RenderUtil.renderJson(response, result);
                return new ModelAndView();
            }

        });
    }

    /**
     * 拦截器注册---并指定拦截器的拦截路径
     *
     * @param registry
     */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry
//                .addInterceptor(new RestApiInterceptor())
//                .addPathPatterns("/**")
//                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/swagger-ui.html/**")
//                .excludePathPatterns("/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs")
//                .excludePathPatterns("/sysUser/login", "/sysUser/checkUserByMobile")
//                .excludePathPatterns("/*/downLoad", "/*/export")
//                .excludePathPatterns("/xibei/*/export")
//                .excludePathPatterns("/*/export*")
//                .excludePathPatterns("/*/exportProduction")
//                .excludePathPatterns("/*/exportMonthReport")
//                .excludePathPatterns("/*/exportSpecialReport")
//                .excludePathPatterns("/*/exportSeniorReport")
////                .excludePathPatterns("/**/insertdata")
//                .excludePathPatterns("/*/exportDailyInputReport");
//
//    }
}
